/*
 * Copyright © 2016 北京易酒批电子商务有限公司. All rights reserved.
 */
package com.cloud.alibaba.common.page;


import cn.hutool.http.HttpStatus;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;

import java.io.StringWriter;

@Data
@NoArgsConstructor
public class BaseResult {
    /**
     * 相应状态结果码
     */
    private Integer code;
    /**
     * 异常基本信息
     */
    private String message;
    /**
     * 异常详细信息
     */
    private String detailMessage;


    public BaseResult(Integer code) {
        this.code = code;
    }

    public BaseResult(String message, Integer code) {
        this.message = message;
        this.code = code;
    }

    public BaseResult(Exception exception) {
        this.code = HttpStatus.HTTP_INTERNAL_ERROR;
        this.message = getFinalMessage(exception);
        StringWriter sw = new StringWriter();
        exception.printStackTrace(new java.io.PrintWriter(sw));
        this.detailMessage = sw.toString();
    }

    public BaseResult(String message, Exception exception) {
        this(exception);
        this.message = message;
    }

    public static BaseResult getSuccessResult() {
        return new BaseResult(HttpStatus.HTTP_OK);
    }

    /**
     * 获取最末层的异常提示信息
     * @param exception 异常
     * @return 最末层的异常提示信息
     */
    public static String getFinalMessage(Exception exception) {
        String message = exception.getMessage();
        Throwable cause = exception.getCause();
        // 循环3层获取到异常提示信息
        int i = 0;
        while (null != cause && i < 3) {
            message = cause.getMessage();
            cause = cause.getCause();
            i++;
        }
        return message;
    }

    /**
     * 超过500长度截断返回消息
     * @param message
     * @return String
     */
    public static String getTruncateMessage(String message) {
        String truncateMessage = message;
        if (StringUtils.hasText(message) && message.length() > 500) {
            truncateMessage = message.substring(0, 499);
            truncateMessage = truncateMessage + "...";
        }
        return truncateMessage;
    }
}
